﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using MapsterMapper;
using System.Reflection;
using xxx.Candidates.System.Common.Redis;
using xxx.Candidates.System.Hostd.Extensions;
using xxx.Candidates.System.Hostd.Setup;
using Newtonsoft.Json;
using xxx.Candidates.System.Hostd.Global;
using Microsoft.AspNetCore.HttpOverrides;

namespace xxx.Candidates.System.Hostd
{
    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //启用数据库链接
            services.AddSqlsugarSetup();

            //跨域设置
            services.AddCorsSetup();

            services.AddSwaggerSetup();

            //注入 HTTPCONTEXT
            services.AddHttpContextAccessor();

            //注入 TokenManager
            services.AddScoped<TokenManager>();

            //注入实体映射服务
            services.AddScoped<IMapper, ServiceMapper>();

            //注册REDIS 服务
            RedisServer.Initalize();

            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            //配置Json格式
            services.AddMvc().AddNewtonsoftJson(options =>
            {
                // 忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                // 不使用驼峰
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                // 设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                // 如字段为null值，该字段不会返回到前端
                //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            //注入全局异常过滤
            services.AddControllers(options =>
            {
                //全局异常过滤
                options.Filters.Add<GlobalExceptions>();
                //全局日志
                options.Filters.Add<GlobalActionMonitor>();

            })
            .ConfigureApiBehaviorOptions(options =>
            {
                //抑制系统自带模型验证
                options.SuppressModelStateInvalidFilter = true;
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            };

            // 跨域设置
            app.UseCorsSetup();
            // 说明文档
            app.UseSwaggerSetup();
            // 使用cookie
            app.UseCookiePolicy();
            // 处理反向代理请求头
            app.UseForwardedHeaders();
            // 使用静态文件
            app.UseStaticFiles();
            // 使用Routing
            app.UseRouting();
            // 使用相应缓存中间件
            app.UseResponseCaching();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        #region 自动注入服务
        public void ConfigureContainer(ContainerBuilder builder)
        {
            var assemblysServices = Assembly.Load("xxx.Candidates.System.Interfaces");
            builder.RegisterAssemblyTypes(assemblysServices)
                .InstancePerDependency()
               .AsImplementedInterfaces()
               .EnableInterfaceInterceptors();
        }
        #endregion
    }
}
